package com.googlecode.garbagecan.clickstudy.page.customer;

import com.googlecode.garbagecan.clickstudy.BorderTemplate;
import com.googlecode.garbagecan.clickstudy.service.customer.CustomerService;
import com.googlecode.garbagecan.clickstudy.entity.customer.Customer;
import org.apache.click.control.*;
import org.apache.click.extras.control.EmailField;
import org.apache.click.util.Bindable;

public class EditCustomer extends BorderTemplate {
	@Bindable protected String title = "Edit Customer";
	
	@Bindable protected Form form = new Form("form");

	@Bindable protected Integer id;

	private HiddenField idField = new HiddenField("id", Integer.class);

	public EditCustomer() {
		form.add(idField);

		FieldSet fieldSet = new FieldSet("customer");
		form.add(fieldSet);

		TextField nameField = new TextField("name", true);
		nameField.setMinLength(5);
		nameField.setFocus(true);
		fieldSet.add(nameField);

		fieldSet.add(new EmailField("email"));

		CustomerService customerService = CustomerService.getInstance();
		Select investmentSelect = new Select("investments");
		investmentSelect.add(Option.EMPTY_OPTION);
		investmentSelect.addAll(customerService.getInvestmentCatetories());
		fieldSet.add(investmentSelect);
		
		fieldSet.add(new Checkbox("active"));

		form.add(new Submit("ok", "  OK  ", this, "onOkClick"));
		form.add(new Submit("cancel", this, "onCancelClick"));
	}

	@Override
	public void onGet() {
		if (id != null) {
			Customer customer = CustomerService.getInstance().find(id);
			if (customer != null) {
				form.copyFrom(customer);
			}
		}
	}

    public boolean onOkClick() {
		if (form.isValid()) {
			Integer id = (Integer) idField.getValueObject();
			Customer customer = CustomerService.getInstance().find(id);
			if (customer == null) {
				customer = new Customer();
			}
			form.copyTo(customer);

			CustomerService.getInstance().update(customer);
			setRedirect(Customers.class);
			return false;
		} else {
			return true;
		}
	}

	public boolean onCancelClick() {
		setRedirect(Customers.class);
		return false;
	}
}
